//
//  Sequenceboard.m
//  警用舆情平台
//
//  Created by 魏强 on 15/5/17.
//  Copyright (c) 2015年 魏强. All rights reserved.
//

#import "Sequenceboard.h"
@interface Sequenceboard ()
{
    BOOL contain;
    CGPoint startPoint;//按钮每动一次的中心点
    CGPoint originPoint;//按钮的初始中心点
}
@property (strong , nonatomic) NSMutableArray *itemArray;
@property (nonatomic, strong) NSMutableArray *tempArr;

@property (nonatomic, weak) UIView *sequenceView;
@property (nonatomic, strong) NSDictionary *dic;

@end
@implementation Sequenceboard

- (NSMutableArray *)itemArray
{
    if (!_itemArray) {
        _itemArray = [NSMutableArray array];
    }
    return _itemArray;
}
+ (instancetype)SequenceboardWithFrame:(CGRect)frame
{
    
    return [[self alloc]initWithFrame:frame];
    
}
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = BackGroundColor;
        
    }
    return self;
}
//用set方法来设置顺序版
- (void)setSequenceArr:(NSArray *)sequenceArr
{
    _sequenceArr = sequenceArr;
    [self.itemArray removeAllObjects];
    self.sequenceView = nil;
    //添加白色底面
    UIView *sequenceView = [[UIView alloc]init];
    self.sequenceView = sequenceView;
    sequenceView.backgroundColor = [UIColor whiteColor];
    CGFloat magin = 8;
    for (int i = 0; i < sequenceArr.count; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        btn.width = (screenW - 6* magin)/5.0;
        btn.height = 20;
        btn.x = i%5 * (btn.width + magin) +magin;
        btn.y = i/5 *(btn.height +magin) +magin;
        btn.tag = 10+i;
        if (btn.tag == 10) {
            [btn setTitleColor: WQColor(83, 88, 98) forState:UIControlStateNormal];
            
        }else
        {
            btn.layer.borderWidth = 1;
            btn.layer.cornerRadius = 4;
            btn.layer.borderColor = KDColor.CGColor;
            [btn setTitleColor:KDColor forState:UIControlStateNormal];

        }
      
        btn.titleLabel.font = [UIFont systemFontOfSize:18];
        [btn setTitle:sequenceArr[i] forState:UIControlStateNormal];
        
//        添加长按事件
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(btnLong:)];
        longPress.minimumPressDuration = 0.5; //定义长按的时间
        [btn addGestureRecognizer:longPress];
        
        [self.itemArray addObject:btn];

        [sequenceView addSubview:btn];
        btn.tintColor = [UIColor clearColor];
    }
    NSDictionary *dic = [NSDictionary dictionaryWithObjects:self.itemArray forKeys:sequenceArr];
    self.dic = dic;
//    NSLog(@"%@", dic);
    UIButton *btn = (UIButton *) [sequenceView viewWithTag:sequenceArr.count +9];
    sequenceView.frame = CGRectMake(0, 0, screenW, CGRectGetMaxY(btn.frame) +20);
    
    [self addSubview:sequenceView];
}
//通过长按手势来调节topic按钮的顺序
- (void)btnLong:(UILongPressGestureRecognizer *)longpress
{
  //长按后被激起的点
    UIButton *btn = (UIButton *)longpress.view;
    if (!self.tempArr) {
        self.tempArr = [NSMutableArray arrayWithArray:self.sequenceArr];
    }
 //如果是巡查按钮，那么就不执行操作
    if (btn.tag == 10) {
        return;
    }
    NSInteger i = 0;
    //算出这个btn所在位置
    for (NSString *topic in _tempArr) {
        if ([topic isEqualToString: btn.titleLabel.text]) {
            break;
        }
        i++;

    }

    if ([longpress state] == UIGestureRecognizerStateBegan) {//开始长按的时候
        startPoint = [longpress locationInView:longpress.view];//触摸开始时的位置（相对系是被触摸的View）
        originPoint = btn.center;//被触摸的对象的中心
        [UIView animateWithDuration:0.5 animations:^{
            btn.transform = CGAffineTransformMakeScale(1.1, 1.1);//让它变大变淡
            btn.alpha = 0.7;
        }];
    }else if ([longpress state] == UIGestureRecognizerStateChanged){
        CGPoint newPoint = [longpress locationInView:longpress.view];
        
        CGFloat deltaX = newPoint.x - startPoint.x;
        CGFloat deltaY = newPoint.y - startPoint.y;
        btn.center = CGPointMake(btn.centerX + deltaX, btn.centerY +deltaY);//让触摸点始终处于同一位置
        NSInteger index = [self indexOfPoint:btn.center withButton:btn];
        if (index <0) {
            contain = NO;
        }else{
            UIButton *button = _itemArray[index];
            [_tempArr exchangeObjectAtIndex:i withObjectAtIndex:index];
            [UIView animateWithDuration:0.2 animations:^{
                CGPoint tempPoint = CGPointZero;
                tempPoint = button.center;
                button.center = originPoint;
                btn.center = tempPoint;
                originPoint = btn.center;
                contain = YES;
            }];
//            i = index;
        }
    }else if (longpress.state == UIGestureRecognizerStateEnded)
    {
        self.sequenceArr = _tempArr;
        [[NSUserDefaults standardUserDefaults] setValue:_tempArr forKey:SEQUENCEARR];
//        NSLog(@"%@",_tempArr);
        [UIView animateWithDuration:0.3 animations:^{
            btn.transform = CGAffineTransformIdentity;
            btn.alpha = 1.0;
            if (!contain) {
                btn.center = originPoint;
            }
        }];
    }
}
- (void)adjustSequance
{
    self.itemArray = nil;
    for (NSString *str in self.tempArr) {
        UIButton *btn = (UIButton *)[self.dic valueForKey:str];
        [self.itemArray addObject:btn];
    }
    NSDictionary *dic = [NSDictionary dictionaryWithObjects:self.itemArray forKeys:self.tempArr];
    self.dic = dic;
}
/**
 *  @param point 被拖动的btn当前的center
 *  @param btn   被拖动的btn
 *  @return
 */
- (NSInteger)indexOfPoint:(CGPoint)point withButton:(UIButton *)btn
{
    [self adjustSequance];
    for (NSInteger i = 0; i < self.itemArray.count; i++)
    {
        UIButton *button = _itemArray[i];
        if (button != btn && button.tag != 10) {
            if (CGRectContainsPoint(button.frame, point)) {
                return i;
            }
        }
    }
    return -1;
}

@end
